package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Roger
 * @date 2020/8/15 10:57
 * @description
 */
@Component
public class CglibProxyFactory {

    @Autowired
    private AccountService accountService;

    @Autowired
    private TransactionManager transactionManager;

    public AccountService getCglibProxy() {

        AccountService o = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println(method.getName());
                Object invoke = null;
                try {
                    transactionManager.startTransaction();
                    invoke = method.invoke(accountService, objects);
                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollBack();
                    e.printStackTrace();
                } finally {
                    transactionManager.release();
                }
                return invoke;
            }
        });
        return o;

    }


}
